<template>
  <view class="verify-container">
    <!-- 验证状态头部 -->
    <view class="status-header" :class="statusClass">
      <view class="status-icon">
        <uni-icons :type="statusIcon" size="60" color="#fff"></uni-icons>
      </view>
      <view class="status-title">{{ statusTitle }}</view>
      <view class="status-desc">{{ statusDesc }}</view>
    </view>

    <!-- 预约信息卡片 -->
    <view class="info-card" v-if="appointmentInfo">
      <view class="card-header">
        <text class="card-title">预约信息</text>
        <view class="qr-badge" :class="qrBadgeClass">
          {{ qrBadgeText }}
        </view>
      </view>
      
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">预约编号</text>
          <text class="info-value">{{ appointmentInfo.applyNo }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">商户名称</text>
          <text class="info-value">{{ appointmentInfo.merchantName || '未知商户' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">入场地点</text>
          <text class="info-value">{{ appointmentInfo.entryPlace }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">预约时间</text>
          <text class="info-value">{{ formatDateTime(appointmentInfo.entryTime) }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">车辆号码</text>
          <text class="info-value">{{ appointmentInfo.vehicleNo }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">联系电话</text>
          <text class="info-value">{{ appointmentInfo.contactPhone }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">货物总量</text>
          <text class="info-value">{{ appointmentInfo.totalAmount }}kg</text>
        </view>
        <view class="info-item">
          <text class="info-label">查验状态</text>
          <text class="info-value" :class="checkStatusClass">
            {{ checkStatusText }}
          </text>
        </view>
      </view>
    </view>

    <!-- 过期提示 -->
    <view class="expired-alert" v-if="appointmentInfo && appointmentInfo.isExpired">
      <uni-icons type="closeempty" size="20" color="#ff4d4f"></uni-icons>
      <text class="alert-text">{{ appointmentInfo.expiredTip || '预约时间已过期，请重新预约' }}</text>
    </view>
    
    <!-- 抽检提示 -->
    <view class="inspection-alert" v-if="appointmentInfo && appointmentInfo.needInspection && !appointmentInfo.isExpired">
      <uni-icons type="info-filled" size="20" color="#faad14"></uni-icons>
      <text class="alert-text">{{ appointmentInfo.inspectionTip }}</text>
    </view>

    <!-- 商品明细 -->
    <view class="goods-card" v-if="appointmentInfo && appointmentInfo.goodsList">
      <view class="card-header">
        <text class="card-title">商品明细</text>
      </view>
      <view class="goods-list">
        <view class="goods-item" v-for="(item, index) in appointmentInfo.goodsList" :key="index">
         
          <view class="goods-info">
            <text class="goods-name">{{ item.goodsName || '商品' + (index + 1) }}</text>
            <text class="goods-quantity">{{ item.quantity }}{{ item.unit || 'kg' }}</text>
          </view>
          <view class="goods-extra">
            <text class="goods-supplier">{{ item.supplierName || '供货商' }}</text>
            <text class="goods-origin">{{ item.originPlace || '产地未知' }}</text>
          </view>

          <!-- 资质图片显示区域 -->
<view class="product-qualifications">
  <view class="qualifications-title">产品资质</view>
  <view class="qualifications-container">
    <!-- 进货凭证 -->
    <view class="qualification-item" v-if="item.purchaseVoucher">
      <text class="qualification-label">进货凭证</text>
      <image 
        :src="item.purchaseVoucher" 
        mode="aspectFill" 
        class="qualification-image" 
        @click="previewImage(item.purchaseVoucher)"
      ></image>
    </view>
    
    <!-- 承诺达标合格证 -->
    <view class="qualification-item" v-if="item.qualificationCert">
      <text class="qualification-label">承诺达标合格证</text>
      <image 
        :src="item.qualificationCert" 
        mode="aspectFill" 
        class="qualification-image" 
        @click="previewImage(item.qualificationCert)"
      ></image>
    </view>
    
    <!-- 动物检疫合格证明 -->
    <view class="qualification-item" v-if="item.animalQuarantineCert">
      <text class="qualification-label">动物检疫合格证明</text>
      <image 
        :src="item.animalQuarantineCert" 
        mode="aspectFill" 
        class="qualification-image" 
        @click="previewImage(item.animalQuarantineCert)"
      ></image>
    </view>
    
    <!-- 肉品品质检验合格证 -->
    <view class="qualification-item" v-if="item.meatQualityCert">
      <text class="qualification-label">肉品品质检验合格证</text>
      <image 
        :src="item.meatQualityCert" 
        mode="aspectFill" 
        class="qualification-image" 
        @click="previewImage(item.meatQualityCert)"
      ></image>
    </view>
  </view>
</view>


        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons" v-if="appointmentInfo">
      <!-- 允许入场按钮（绿码且未过期） -->
      <button 
        v-if="appointmentInfo.qrColor === '0' && appointmentInfo.checkStatus !== '1' && !appointmentInfo.isExpired" 
        class="action-btn primary"
        @click="confirmEntry"
      >
        <uni-icons type="checkmarkempty" size="20" color="#fff"></uni-icons>
        <text class="btn-text">确认入场</text>
      </button>
      
      <!-- 开始抽检按钮（黄码且未过期，且用户是抽检员） -->
      <button 
        v-if="isInspector && appointmentInfo.needInspection && appointmentInfo.checkStatus !== '1' && !appointmentInfo.isExpired" 
        class="action-btn warning"
        @click="startInspection"
      >
        <uni-icons type="scan" size="20" color="#fff"></uni-icons>
        <text class="btn-text">开始抽检</text>
      </button>
      
      <!-- 需要抽检但用户不是抽检员的提示 -->
      <view 
        v-if="!isInspector && appointmentInfo.needInspection && appointmentInfo.checkStatus !== '1' && !appointmentInfo.isExpired"
        class="inspection-notice"
      >
        <uni-icons type="info-filled" size="20" color="#faad14"></uni-icons>
        <text class="notice-text">该批货物需要抽检，请通知抽检员处理</text>
      </view>
      
      <!-- 已查验提示 -->
      <view v-if="appointmentInfo.checkStatus === '1'" class="checked-tips">
        <uni-icons type="checkmarkempty" size="20" color="#52c41a"></uni-icons>
        <text class="tips-text">该预约已完成查验</text>
      </view>
      
      <!-- 返回按钮 -->
      <button class="action-btn default" @click="goBack">
        <uni-icons type="back" size="20" color="#666"></uni-icons>
        <text class="btn-text">返回</text>
      </button>
    </view>

    <!-- 错误提示 -->
    <view class="error-container" v-if="errorMsg">
      <uni-icons type="closeempty" size="60" color="#ff4d4f"></uni-icons>
      <text class="error-title">验证失败</text>
      <text class="error-desc">{{ errorMsg }}</text>
      <button class="retry-btn" @click="retry">重新扫码</button>
    </view>
  </view>
</template>

<script>
import { verifyQrCode, checkAppointment } from '@/api/system/appointment.js'
import storage from '@/utils/storage'
import constant from '@/utils/constant'

export default {
  data() {
    return {
      applyNo: '',
      applyId: '',
      code: '',
      appointmentInfo: null,
      statusTitle: '正在验证...',
      statusDesc: '请稍候，正在验证二维码信息',
      errorMsg: '',
      loading: false,
      isInspector: false  // 是否是抽检员
    }
  },
  computed: {
    // 获取状态样式
    statusClass() {
      if (this.errorMsg) {
        return 'status-error'
      }
      if (this.appointmentInfo) {
        if (this.appointmentInfo.checkStatus === '1') {
          return 'status-checked'
        }
        if (this.appointmentInfo.needInspection) {
          return 'status-warning'
        }
        return 'status-success'
      }
      return 'status-loading'
    },
    
    // 获取状态图标
    statusIcon() {
      if (this.errorMsg) {
        return 'closeempty'
      }
      if (this.appointmentInfo) {
        if (this.appointmentInfo.checkStatus === '1') {
          return 'checkbox'
        }
        if (this.appointmentInfo.needInspection) {
          return 'info-filled'
        }
        return 'checkmarkempty'
      }
      return 'reload'
    },
    
    // 获取二维码徽章样式
    qrBadgeClass() {
      if (!this.appointmentInfo) return ''
      if (this.appointmentInfo.qrColor === '0') return 'badge-green'
      if (this.appointmentInfo.qrColor === '1') return 'badge-yellow'
      if (this.appointmentInfo.qrColor === '2') return 'badge-red'
      return 'badge-yellow'
    },
    
    // 获取二维码徽章文本
    qrBadgeText() {
      if (!this.appointmentInfo) return ''
      if (this.appointmentInfo.qrColor === '0') return '绿码'
      if (this.appointmentInfo.qrColor === '1') return '黄码'
      if (this.appointmentInfo.qrColor === '2') return '红码'
      return '黄码'
    },
    
    // 获取查验状态样式
    checkStatusClass() {
      if (!this.appointmentInfo) return ''
      return this.appointmentInfo.checkStatus === '1' ? 'status-checked' : 'status-unchecked'
    },
    
    // 获取查验状态文本
    checkStatusText() {
      if (!this.appointmentInfo) return '未知'
      return this.appointmentInfo.checkStatus === '1' ? '已查验' : '待查验'
    }
  },
  onLoad(options) {
    // 获取扫码参数
    this.applyNo = options.applyNo || ''
    this.applyId = options.applyId || ''
    this.code = options.code || ''
    
    // 检查用户角色
    this.checkUserRole()
    
    if (!this.applyNo || !this.code) {
      this.errorMsg = '二维码参数错误'
      this.statusTitle = '验证失败'
      this.statusDesc = '无效的二维码'
      return
    }
    
    // 验证二维码
    this.verifyQrCode()
  },
  methods: {
    // 预览图片
previewImage(imageUrl) {
  if (imageUrl) {
    uni.previewImage({
      urls: [imageUrl],
      current: 0
    })
  }
},
    // 检查用户角色
    checkUserRole() {
      // 获取用户角色
      const roles = storage.get(constant.roles) || []
      const roleKeys = roles.map(role => {
        if (typeof role === 'object' && role.roleKey) {
          return role.roleKey
        }
        return role
      })
      
      // 判断是否是抽检员
      this.isInspector = roleKeys.includes('inspector') || roleKeys.includes('market_safety_officer')
      console.log('用户角色:', roleKeys, '是否是抽检员:', this.isInspector);
    },
    
    // 验证二维码
    async verifyQrCode() {
      try {
        this.loading = true
        const response = await verifyQrCode({
          applyNo: this.applyNo,
          code: this.code
        })
        
        if (response.code === 200) {
          this.appointmentInfo = response.data
          this.statusTitle = '验证成功'
          this.statusDesc = this.getVerifyDesc()
          this.errorMsg = ''
        } else {
          this.errorMsg = response.msg || '验证失败'
          this.statusTitle = '验证失败'
          this.statusDesc = '二维码验证未通过'
        }
      } catch (error) {
        console.error('验证失败:', error)
        this.errorMsg = '网络错误，请重试'
        this.statusTitle = '验证失败'
        this.statusDesc = '无法连接到服务器'
      } finally {
        this.loading = false
      }
    },
    
    // 确认入场
    confirmEntry() {
      uni.showModal({
        title: '确认入场',
        content: '确定允许该车辆入场吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await checkAppointment({
                applyId: this.applyId || this.appointmentInfo.applyId,
                checkStatus: '1'
              })
              
              if (response.code === 200) {
                uni.showToast({
                  title: '入场成功',
                  icon: 'success'
                })
                
                // 更新状态
                this.appointmentInfo.checkStatus = '1'
                this.statusTitle = '入场成功'
                this.statusDesc = '车辆已允许入场'
              } else {
                uni.showToast({
                  title: response.msg || '操作失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 开始抽检
    startInspection() {
      // 跳转到抽检页面
      uni.navigateTo({
        url: `/pages/check/inspection?applyId=${this.applyId || this.appointmentInfo.applyId}&applyNo=${this.applyNo}`
      })
    },
    
    // 获取验证描述
    getVerifyDesc() {
      if (!this.appointmentInfo) return ''
      
      if (this.appointmentInfo.checkStatus === '1') {
        return '该预约已完成查验'
      }
      
      if (this.appointmentInfo.needInspection) {
        return '需要进行货物抽检'
      }
      
      return '验证通过，可以入场'
    },
    
    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    
    // 重新扫码
    retry() {
      uni.scanCode({
        success: (res) => {
          // 解析扫码结果
          const result = res.result
          if (result.includes('/pages/check/verify')) {
            // 重新加载页面
            const url = new URL(result, 'http://example.com')
            const params = new URLSearchParams(url.search)
            
            this.applyNo = params.get('applyNo') || ''
            this.code = params.get('code') || ''
            this.applyId = params.get('applyId') || ''
            
            this.errorMsg = ''
            this.verifyQrCode()
          } else {
            uni.showToast({
              title: '无效的二维码',
              icon: 'none'
            })
          }
        }
      })
    },
    
    // 返回
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
/* 产品资质样式 */
.product-qualifications {
  padding: 20rpx 0;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);
}

.qualifications-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 15rpx;
}

.qualifications-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.qualification-item {
  flex: 1;
  min-width: 45%;
}

.qualification-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.qualification-image {
  width: 100%;
  height: 150rpx;
  border-radius: 8rpx;
  border: 1rpx solid #e6e6e6;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}
.verify-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.status-header {
  padding: 60rpx 30rpx;
  text-align: center;
  color: #fff;
}

.status-loading {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.status-success {
  background: linear-gradient(135deg, #52c41a, #73d13d);
}

.status-warning {
  background: linear-gradient(135deg, #faad14, #ffc53d);
}

.status-error {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
}

.status-checked {
  background: linear-gradient(135deg, #13c2c2, #36cfc9);
}

.status-icon {
  margin-bottom: 30rpx;
}

.status-title {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.status-desc {
  font-size: 28rpx;
  opacity: 0.9;
}

.info-card, .goods-card {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.qr-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: bold;
  color: #fff;
}

.badge-green {
  background-color: #52c41a;
}

.badge-yellow {
  background-color: #faad14;
}

.badge-red {
  background-color: #ff4d4f;
}

.info-list {
  /* 信息列表样式 */
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #666;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.status-checked {
  color: #52c41a;
}

.status-unchecked {
  color: #faad14;
}

.inspection-alert {
  display: flex;
  align-items: center;
  background-color: #fffbe6;
  border: 2rpx solid #ffe58f;
  border-radius: 8rpx;
  margin: 20rpx;
  padding: 20rpx;
}

.expired-alert {
  display: flex;
  align-items: center;
  background-color: #fff1f0;
  border: 2rpx solid #ffccc7;
  border-radius: 8rpx;
  margin: 20rpx;
  padding: 20rpx;
}

.expired-alert .alert-text {
  margin-left: 15rpx;
  font-size: 28rpx;
  color: #cf1322;
}

.alert-text {
  margin-left: 15rpx;
  font-size: 28rpx;
  color: #d48806;
}

.goods-list {
  /* 商品列表样式 */
}

.goods-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.goods-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.goods-quantity {
  font-size: 28rpx;
  color: #1890ff;
  font-weight: bold;
}

.goods-extra {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-supplier, .goods-origin {
  font-size: 24rpx;
  color: #999;
}

.action-buttons {
  padding: 30rpx 20rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: 500;
}

.action-btn.primary {
  background-color: #52c41a;
  color: #fff;
}

.action-btn.warning {
  background-color: #faad14;
  color: #fff;
}

.action-btn.default {
  background-color: #fff;
  color: #666;
  border: 2rpx solid #d9d9d9;
}

.btn-text {
  margin-left: 10rpx;
}

.checked-tips {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  background-color: #f6ffed;
  border-radius: 8rpx;
}

.tips-text {
  margin-left: 10rpx;
  font-size: 30rpx;
  color: #52c41a;
}

.inspection-notice {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  background-color: #fff7e6;
  border-radius: 8rpx;
  border: 2rpx solid #faad14;
}

.notice-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #faad14;
}

.error-container {
  padding: 100rpx 40rpx;
  text-align: center;
}

.error-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin: 30rpx 0 20rpx;
}

.error-desc {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 60rpx;
}

.retry-btn {
  width: 300rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1890ff;
  color: #fff;
  border-radius: 40rpx;
  margin: 0 auto;
}
</style>